import {
  Controller,
  Get,
  Post,
  Put,
  Delete,
  Body,
  Param,
  Query,
  UseGuards,
  UseInterceptors,
  HttpStatus,
  HttpCode,
  ParseUUIDPipe,
  ValidationPipe,
  UsePipes,
  // CacheInterceptor,
  // CacheTTL,
  UploadedFile,
  ParseFilePipe,
  MaxFileSizeValidator,
  FileTypeValidator,
  Req,
  Res,
  StreamableFile
} from '@nestjs/common'
import { ApiTags, ApiOperation, ApiResponse, ApiBearerAuth, ApiConsumes, ApiQuery } from '@nestjs/swagger'
import type { Request, Response } from 'express'
import { LogLevel } from '../../logger/decorators/log.decorator'
// import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
// import { RolesGuard } from '../auth/guards/roles.guard';
// import { Roles } from '../auth/decorators/roles.decorator';
// import { ResponseInterceptor } from '../../common/interceptors/response.interceptor';
// import { LoggingInterceptor } from '../../common/interceptors/logging.interceptor';
import { FileInterceptor } from '@nestjs/platform-express'
import { Throttle } from '@nestjs/throttler'
import {
  SystemConfigDto,
  CreateConfigDto,
  UpdateConfigDto,
  QueryConfigDto,
  BulkConfigOperationDto,
  SystemInfoDto,
  HealthCheckDto,
  LogConfigDto
} from '../../common/dto/system.dto'
import { ResponseDto as ApiResponseDto } from '../../common/dto/base.dto'
import { UserRole } from '../../common/decorators/auth.decorator'

/**
 * 系统管理控制器
 * 负责系统配置、健康检查、日志管理等功能
 */
@ApiTags('系统管理')
@Controller('api/system')
// @UseGuards(JwtAuthGuard, RolesGuard)
// @UseInterceptors(ResponseInterceptor, LoggingInterceptor)
@ApiBearerAuth()
export class SystemController {
  constructor() {} // private readonly logService: LogService, // private readonly healthService: HealthService, // private readonly configService: ConfigService, // private readonly systemService: SystemService,

  /**
   * 获取系统信息
   */
  @Get('info')
  @ApiOperation({ summary: '获取系统信息' })
  @ApiResponse({
    status: HttpStatus.OK,
    description: '系统信息获取成功',
    type: ApiResponseDto<SystemInfoDto>
  })
  // @Roles(UserRole.ADMIN, UserRole.SUPER_ADMIN)
  // @UseInterceptors(CacheInterceptor)
  // @CacheTTL(300) // 5分钟缓存
  async getSystemInfo(): Promise<ApiResponseDto<SystemInfoDto>> {
    // const systemInfo = await this.systemService.getSystemInfo();
    const memoryUsage = process.memoryUsage()
    const systemInfo: SystemInfoDto = {
      version: '1.0.0',
      buildTime: new Date().toISOString(),
      environment: process.env.NODE_ENV || 'development',
      nodeVersion: process.version,
      platform: process.platform,
      architecture: process.arch,
      uptime: process.uptime(),
      memory: {
        used: memoryUsage.heapUsed,
        total: memoryUsage.heapTotal,
        free: memoryUsage.heapTotal - memoryUsage.heapUsed,
        usage: (memoryUsage.heapUsed / memoryUsage.heapTotal) * 100
      },
      cpu: {
        model: 'Intel Core i7',
        cores: 8,
        usage: 25.5
      },
      disk: {
        used: 50 * 1024 * 1024 * 1024, // 50GB
        total: 500 * 1024 * 1024 * 1024, // 500GB
        free: 450 * 1024 * 1024 * 1024, // 450GB
        usage: 10
      },
      database: {
        status: 'connected',
        responseTime: 10
      },
      cache: {
        status: 'connected',
        responseTime: 5
      },
      storage: {
        status: 'available',
        responseTime: 15
      }
    }

    return {
      code: HttpStatus.OK,
      message: '系统信息获取成功',
      data: systemInfo,
      timestamp: new Date().toISOString()
    }
  }

  /**
   * 健康检查
   */
  @Get('health')
  @ApiOperation({ summary: '系统健康检查' })
  @ApiResponse({
    status: HttpStatus.OK,
    description: '健康检查完成',
    type: ApiResponseDto<HealthCheckDto>
  })
  @HttpCode(HttpStatus.OK)
  async healthCheck(): Promise<ApiResponseDto<HealthCheckDto>> {
    // const healthStatus = await this.healthService.check();
    const healthStatus: HealthCheckDto = {
      status: 'healthy',
      timestamp: new Date(),
      checks: {
        database: { status: 'pass', responseTime: 10, message: 'Connection successful' },
        redis: { status: 'pass', responseTime: 5, message: 'Connection successful' },
        storage: { status: 'pass', responseTime: 15, message: 'Storage accessible' },
        memory: { status: 'pass', responseTime: 1, message: 'Memory usage normal' },
        disk: { status: 'pass', responseTime: 2, message: 'Disk space sufficient' }
      },
      info: {
        version: '1.0.0',
        uptime: process.uptime(),
        environment: process.env.NODE_ENV || 'development'
      }
    }

    return {
      code: HttpStatus.OK,
      message: '健康检查完成',
      data: healthStatus,
      timestamp: new Date().toISOString()
    }
  }

  /**
   * 获取系统配置列表
   */
  @Get('configs')
  @ApiOperation({ summary: '获取系统配置列表' })
  @ApiResponse({
    status: HttpStatus.OK,
    description: '配置列表获取成功',
    type: ApiResponseDto<SystemConfigDto[]>
  })
  @ApiQuery({ name: 'type', required: false, description: '配置类型' })
  @ApiQuery({ name: 'status', required: false, description: '配置状态' })
  @ApiQuery({ name: 'search', required: false, description: '搜索关键词' })
  // @Roles(UserRole.ADMIN, UserRole.SUPER_ADMIN)
  // @UseInterceptors(CacheInterceptor)
  // @CacheTTL(60) // 1分钟缓存
  async getConfigs(@Query(ValidationPipe) query: QueryConfigDto): Promise<ApiResponseDto<SystemConfigDto[]>> {
    // const configs = await this.systemService.getConfigs(query);
    const configs: SystemConfigDto[] = [
      {
        siteName: 'My CMS System',
        siteTitle: 'My CMS System',
        siteUrl: 'https://example.com'
      },
      {
        siteName: 'Another Site',
        siteTitle: 'Another Site Title',
        siteUrl: 'https://another-example.com'
      }
    ]

    return {
      code: HttpStatus.OK,
      message: '配置列表获取成功',
      data: configs,
      timestamp: new Date().toISOString()
    }
  }

  /**
   * 获取单个配置
   */
  @Get('configs/:id')
  @ApiOperation({ summary: '获取单个配置' })
  @ApiResponse({
    status: HttpStatus.OK,
    description: '配置获取成功',
    type: ApiResponseDto<SystemConfigDto>
  })
  // @Roles(UserRole.ADMIN, UserRole.SUPER_ADMIN)
  async getConfig(@Param('id', ParseUUIDPipe) id: string): Promise<ApiResponseDto<SystemConfigDto>> {
    // const config = await this.systemService.getConfigById(id);
    const config: SystemConfigDto = {
      siteName: 'My CMS System',
      siteTitle: 'My CMS System',
      siteUrl: 'https://example.com'
    }

    return {
      code: HttpStatus.OK,
      message: '配置获取成功',
      data: config,
      timestamp: new Date().toISOString()
    }
  }

  /**
   * 创建配置
   */
  @Post('configs')
  @ApiOperation({ summary: '创建配置' })
  @ApiResponse({
    status: HttpStatus.CREATED,
    description: '配置创建成功',
    type: ApiResponseDto<SystemConfigDto>
  })
  // @Roles(UserRole.SUPER_ADMIN)
  @HttpCode(HttpStatus.CREATED)
  async createConfig(@Body(ValidationPipe) createConfigDto: CreateConfigDto): Promise<ApiResponseDto<SystemConfigDto>> {
    // const config = await this.systemService.createConfig(createConfigDto);
    const config: SystemConfigDto = {
      siteName: 'New Site',
      siteTitle: 'New Site Title',
      siteUrl: 'https://example.com'
    }

    return {
      code: HttpStatus.CREATED,
      message: '配置创建成功',
      data: config,
      timestamp: new Date().toISOString()
    }
  }

  /**
   * 更新配置
   */
  @Put('configs/:id')
  @ApiOperation({ summary: '更新配置' })
  @ApiResponse({
    status: HttpStatus.OK,
    description: '配置更新成功',
    type: ApiResponseDto<SystemConfigDto>
  })
  // @Roles(UserRole.ADMIN, UserRole.SUPER_ADMIN)
  async updateConfig(
    @Param('id', ParseUUIDPipe) id: string,
    @Body(ValidationPipe) updateConfigDto: UpdateConfigDto
  ): Promise<ApiResponseDto<SystemConfigDto>> {
    // const config = await this.systemService.updateConfig(id, updateConfigDto);
    const config: SystemConfigDto = {
      siteName: 'Updated Site Name',
      siteTitle: 'Updated Site Title',
      siteUrl: 'https://updated-example.com'
    }

    return {
      code: HttpStatus.OK,
      message: '配置更新成功',
      data: config,
      timestamp: new Date().toISOString()
    }
  }

  /**
   * 删除配置
   */
  @Delete('configs/:id')
  @ApiOperation({ summary: '删除配置' })
  @ApiResponse({
    status: HttpStatus.OK,
    description: '配置删除成功'
  })
  // @Roles(UserRole.SUPER_ADMIN)
  async deleteConfig(@Param('id', ParseUUIDPipe) id: string): Promise<ApiResponseDto<null>> {
    // await this.systemService.deleteConfig(id);

    return {
      code: HttpStatus.OK,
      message: '配置删除成功',
      data: null,
      timestamp: new Date().toISOString()
    }
  }

  /**
   * 批量操作配置
   */
  @Post('configs/bulk')
  @ApiOperation({ summary: '批量操作配置' })
  @ApiResponse({
    status: HttpStatus.OK,
    description: '批量操作完成'
  })
  // @Roles(UserRole.SUPER_ADMIN)
  async bulkConfigOperation(
    @Body(ValidationPipe) bulkOperationDto: BulkConfigOperationDto
  ): Promise<ApiResponseDto<{ affected: number }>> {
    // const result = await this.systemService.bulkConfigOperation(bulkOperationDto);
    const result = { affected: bulkOperationDto.configIds.length }

    return {
      code: HttpStatus.OK,
      message: `批量${bulkOperationDto.operation}操作完成`,
      data: result,
      timestamp: new Date().toISOString()
    }
  }

  /**
   * 重置配置为默认值
   */
  @Post('configs/:id/reset')
  @ApiOperation({ summary: '重置配置为默认值' })
  @ApiResponse({
    status: HttpStatus.OK,
    description: '配置重置成功',
    type: ApiResponseDto<SystemConfigDto>
  })
  // @Roles(UserRole.SUPER_ADMIN)
  async resetConfig(@Param('id', ParseUUIDPipe) id: string): Promise<ApiResponseDto<SystemConfigDto>> {
    // const config = await this.systemService.resetConfig(id);
    const config: SystemConfigDto = {
      siteName: 'CMS System',
      siteTitle: 'CMS System',
      siteUrl: 'https://example.com'
    }

    return {
      code: HttpStatus.OK,
      message: '配置重置成功',
      data: config,
      timestamp: new Date().toISOString()
    }
  }

  /**
   * 导出系统配置
   */
  @Get('configs/export')
  @ApiOperation({ summary: '导出系统配置' })
  @ApiResponse({
    status: HttpStatus.OK,
    description: '配置导出成功'
  })
  // @Roles(UserRole.SUPER_ADMIN)
  async exportConfigs(
    @Query('format') format: 'json' | 'yaml' | 'env' = 'json',
    @Res({ passthrough: true }) res: Response
  ): Promise<StreamableFile> {
    // const configData = await this.systemService.exportConfigs(format);
    const configData = JSON.stringify(
      {
        'site.title': 'My CMS System',
        'email.smtp.host': 'smtp.gmail.com'
      },
      null,
      2
    )

    const buffer = Buffer.from(configData, 'utf-8')
    const filename = `system-config-${new Date().toISOString().split('T')[0]}.${format}`

    res.set({
      'Content-Type': format === 'json' ? 'application/json' : 'text/plain',
      'Content-Disposition': `attachment; filename="${filename}"`
    })

    return new StreamableFile(buffer)
  }

  /**
   * 导入系统配置
   */
  @Post('configs/import')
  @ApiOperation({ summary: '导入系统配置' })
  @ApiConsumes('multipart/form-data')
  @ApiResponse({
    status: HttpStatus.OK,
    description: '配置导入成功'
  })
  // @Roles(UserRole.SUPER_ADMIN)
  @UseInterceptors(FileInterceptor('file'))
  async importConfigs(
    @UploadedFile(
      new ParseFilePipe({
        validators: [
          new MaxFileSizeValidator({ maxSize: 5 * 1024 * 1024 }), // 5MB
          new FileTypeValidator({ fileType: /\.(json|yaml|yml|env)$/ })
        ]
      })
    )
    file: Express.Multer.File
  ): Promise<ApiResponseDto<{ imported: number; skipped: number }>> {
    // const result = await this.systemService.importConfigs(file);
    const result = { imported: 10, skipped: 2 }

    return {
      code: HttpStatus.OK,
      message: '配置导入成功',
      data: result,
      timestamp: new Date().toISOString()
    }
  }

  /**
   * 获取系统日志
   */
  @Get('logs')
  @ApiOperation({ summary: '获取系统日志' })
  @ApiResponse({
    status: HttpStatus.OK,
    description: '日志获取成功'
  })
  @ApiQuery({ name: 'level', required: false, description: '日志级别' })
  @ApiQuery({ name: 'startDate', required: false, description: '开始时间' })
  @ApiQuery({ name: 'endDate', required: false, description: '结束时间' })
  @ApiQuery({ name: 'search', required: false, description: '搜索关键词' })
  // @Roles(UserRole.ADMIN, UserRole.SUPER_ADMIN)
  @Throttle({ default: { limit: 10, ttl: 60000 } }) // 限制每分钟10次请求
  async getLogs(
    @Query('level') level?: string,
    @Query('startDate') startDate?: string,
    @Query('endDate') endDate?: string,
    @Query('search') search?: string,
    @Query('page') page: number = 1,
    @Query('limit') limit: number = 50
  ): Promise<ApiResponseDto<any>> {
    // const logs = await this.logService.getLogs({ level, startDate, endDate, search, page, limit });
    const logs = {
      data: [
        {
          id: '1',
          level: LogLevel.INFO,
          message: 'User logged in successfully',
          timestamp: new Date(),
          context: 'AuthService',
          metadata: { userId: 'user-123', ip: '192.168.1.1' }
        },
        {
          id: '2',
          level: 'error',
          message: 'Database connection failed',
          timestamp: new Date(),
          context: 'DatabaseService',
          metadata: { error: 'Connection timeout' }
        }
      ],
      total: 2,
      page: 1,
      limit: 50,
      totalPages: 1
    }

    return {
      code: HttpStatus.OK,
      message: '日志获取成功',
      data: logs,
      timestamp: new Date().toISOString()
    }
  }

  /**
   * 清理系统日志
   */
  @Delete('logs/cleanup')
  @ApiOperation({ summary: '清理系统日志' })
  @ApiResponse({
    status: HttpStatus.OK,
    description: '日志清理成功'
  })
  // @Roles(UserRole.SUPER_ADMIN)
  async cleanupLogs(
    @Query('days') days: number = 30,
    @Query('level') level?: string
  ): Promise<ApiResponseDto<{ deleted: number }>> {
    // const result = await this.logService.cleanup(days, level);
    const result = { deleted: 1000 }

    return {
      code: HttpStatus.OK,
      message: '日志清理成功',
      data: result,
      timestamp: new Date().toISOString()
    }
  }

  /**
   * 获取日志配置
   */
  @Get('logs/config')
  @ApiOperation({ summary: '获取日志配置' })
  @ApiResponse({
    status: HttpStatus.OK,
    description: '日志配置获取成功',
    type: ApiResponseDto<LogConfigDto>
  })
  // @Roles(UserRole.ADMIN, UserRole.SUPER_ADMIN)
  async getLogConfig(): Promise<ApiResponseDto<LogConfigDto>> {
    // const config = await this.logService.getConfig();
    const config: LogConfigDto = {
      level: LogLevel.INFO,
      enableConsoleLogging: true,
      enableFileLogging: true,
      logFilePath: './logs',
      maxFileSize: 10,
      maxFiles: 14,
      retentionDays: 30,
      format: 'json',
      // datePattern: 'YYYY-MM-DD', // 属性不存在，已注释
      // enableRotation: true, // 属性不存在，已注释
      enableCompression: true,
      // excludePatterns: ['/health', '/metrics'], // 属性不存在，已注释
      // includeMetadata: true, // 属性不存在，已注释
      enableStackTrace: true
      // enableTimestamp: true,
      // timezone: 'Asia/Shanghai',
    }

    return {
      code: HttpStatus.OK,
      message: '日志配置获取成功',
      data: config,
      timestamp: new Date().toISOString()
    }
  }

  /**
   * 更新日志配置
   */
  @Put('logs/config')
  @ApiOperation({ summary: '更新日志配置' })
  @ApiResponse({
    status: HttpStatus.OK,
    description: '日志配置更新成功',
    type: ApiResponseDto<LogConfigDto>
  })
  // @Roles(UserRole.SUPER_ADMIN)
  async updateLogConfig(@Body(ValidationPipe) logConfigDto: LogConfigDto): Promise<ApiResponseDto<LogConfigDto>> {
    // const config = await this.logService.updateConfig(logConfigDto);
    const config = logConfigDto

    return {
      code: HttpStatus.OK,
      message: '日志配置更新成功',
      data: config,
      timestamp: new Date().toISOString()
    }
  }

  /**
   * 系统重启
   */
  @Post('restart')
  @ApiOperation({ summary: '系统重启' })
  @ApiResponse({
    status: HttpStatus.OK,
    description: '系统重启指令已发送'
  })
  // @Roles(UserRole.SUPER_ADMIN)
  @Throttle({ default: { limit: 1, ttl: 300000 } }) // 5分钟内只能重启一次
  async restart(@Body('reason') reason?: string): Promise<ApiResponseDto<null>> {
    // await this.systemService.restart(reason);

    // 记录重启日志
    console.log(`System restart initiated. Reason: ${reason || 'Manual restart'}`)

    // 延迟重启，给客户端时间接收响应
    setTimeout(() => {
      process.exit(0)
    }, 1000)

    return {
      code: HttpStatus.OK,
      message: '系统重启指令已发送',
      data: null,
      timestamp: new Date().toISOString()
    }
  }

  /**
   * 清理系统缓存
   */
  @Post('cache/clear')
  @ApiOperation({ summary: '清理系统缓存' })
  @ApiResponse({
    status: HttpStatus.OK,
    description: '缓存清理成功'
  })
  // @Roles(UserRole.ADMIN, UserRole.SUPER_ADMIN)
  async clearCache(@Body('pattern') pattern?: string): Promise<ApiResponseDto<{ cleared: number }>> {
    // const result = await this.systemService.clearCache(pattern);
    const result = { cleared: 150 }

    return {
      code: HttpStatus.OK,
      message: '缓存清理成功',
      data: result,
      timestamp: new Date().toISOString()
    }
  }

  /**
   * 获取系统统计信息
   */
  @Get('stats')
  @ApiOperation({ summary: '获取系统统计信息' })
  @ApiResponse({
    status: HttpStatus.OK,
    description: '统计信息获取成功'
  })
  // @Roles(UserRole.ADMIN, UserRole.SUPER_ADMIN)
  // @UseInterceptors(CacheInterceptor)
  // @CacheTTL(300) // 5分钟缓存
  async getStats(): Promise<ApiResponseDto<any>> {
    // const stats = await this.systemService.getStats();
    const stats = {
      users: {
        total: 1000,
        active: 850,
        newToday: 25,
        newThisWeek: 150,
        newThisMonth: 600
      },
      content: {
        total: 5000,
        published: 4200,
        draft: 800,
        newToday: 50,
        newThisWeek: 300,
        newThisMonth: 1200
      },
      files: {
        total: 10000,
        totalSize: 5368709120, // 5GB
        images: 7000,
        videos: 500,
        documents: 2500
      },
      system: {
        requests: {
          total: 1000000,
          today: 5000,
          thisWeek: 35000,
          thisMonth: 150000
        },
        errors: {
          total: 1000,
          today: 5,
          thisWeek: 35,
          thisMonth: 150
        },
        performance: {
          avgResponseTime: 120,
          uptime: process.uptime(),
          memoryUsage: process.memoryUsage().heapUsed / 1024 / 1024 // MB
        }
      }
    }

    return {
      code: HttpStatus.OK,
      message: '统计信息获取成功',
      data: stats,
      timestamp: new Date().toISOString()
    }
  }

  /**
   * 系统备份
   */
  @Post('backup')
  @ApiOperation({ summary: '创建系统备份' })
  @ApiResponse({
    status: HttpStatus.OK,
    description: '备份创建成功'
  })
  // @Roles(UserRole.SUPER_ADMIN)
  @Throttle({ default: { limit: 1, ttl: 3600000 } }) // 每小时只能备份一次
  async createBackup(
    @Body('includeFiles') includeFiles: boolean = false,
    @Body('description') description?: string
  ): Promise<ApiResponseDto<{ backupId: string; size: number }>> {
    // const backup = await this.systemService.createBackup({ includeFiles, description });
    const backup = {
      backupId: `backup-${Date.now()}`,
      size: 1024 * 1024 * 100 // 100MB
    }

    return {
      code: HttpStatus.OK,
      message: '备份创建成功',
      data: backup,
      timestamp: new Date().toISOString()
    }
  }

  /**
   * 获取备份列表
   */
  @Get('backups')
  @ApiOperation({ summary: '获取备份列表' })
  @ApiResponse({
    status: HttpStatus.OK,
    description: '备份列表获取成功'
  })
  // @Roles(UserRole.SUPER_ADMIN)
  async getBackups(): Promise<ApiResponseDto<any[]>> {
    // const backups = await this.systemService.getBackups();
    const backups = [
      {
        id: 'backup-1',
        filename: 'backup-2024-01-15.tar.gz',
        size: 104857600, // 100MB
        createdAt: new Date(),
        description: '定期备份',
        includesFiles: false,
        status: 'completed'
      },
      {
        id: 'backup-2',
        filename: 'backup-2024-01-14.tar.gz',
        size: 524288000, // 500MB
        createdAt: new Date(Date.now() - 24 * 60 * 60 * 1000),
        description: '完整备份',
        includesFiles: true,
        status: 'completed'
      }
    ]

    return {
      code: HttpStatus.OK,
      message: '备份列表获取成功',
      data: backups,
      timestamp: new Date().toISOString()
    }
  }

  /**
   * 下载备份文件
   */
  @Get('backups/:id/download')
  @ApiOperation({ summary: '下载备份文件' })
  @ApiResponse({
    status: HttpStatus.OK,
    description: '备份文件下载'
  })
  // @Roles(UserRole.SUPER_ADMIN)
  async downloadBackup(
    @Param('id') backupId: string,
    @Res({ passthrough: true }) res: Response
  ): Promise<StreamableFile> {
    // const backupFile = await this.systemService.getBackupFile(backupId);
    const filename = `backup-${backupId}.tar.gz`
    const buffer = Buffer.from('Mock backup file content', 'utf-8')

    res.set({
      'Content-Type': 'application/gzip',
      'Content-Disposition': `attachment; filename="${filename}"`
    })

    return new StreamableFile(buffer)
  }

  /**
   * 删除备份
   */
  @Delete('backups/:id')
  @ApiOperation({ summary: '删除备份' })
  @ApiResponse({
    status: HttpStatus.OK,
    description: '备份删除成功'
  })
  // @Roles(UserRole.SUPER_ADMIN)
  async deleteBackup(@Param('id') backupId: string): Promise<ApiResponseDto<null>> {
    // await this.systemService.deleteBackup(backupId);

    return {
      code: HttpStatus.OK,
      message: '备份删除成功',
      data: null,
      timestamp: new Date().toISOString()
    }
  }

  /**
   * 系统维护模式
   */
  @Post('maintenance')
  @ApiOperation({ summary: '切换系统维护模式' })
  @ApiResponse({
    status: HttpStatus.OK,
    description: '维护模式状态更新成功'
  })
  // @Roles(UserRole.SUPER_ADMIN)
  async toggleMaintenance(
    @Body('enabled') enabled: boolean,
    @Body('message') message?: string,
    @Body('estimatedDuration') estimatedDuration?: number
  ): Promise<ApiResponseDto<{ enabled: boolean; message?: string }>> {
    // await this.systemService.setMaintenanceMode(enabled, message, estimatedDuration);

    return {
      code: HttpStatus.OK,
      message: `维护模式已${enabled ? '开启' : '关闭'}`,
      data: {
        enabled,
        message: message || (enabled ? '系统正在维护中，请稍后再试' : undefined)
      },
      timestamp: new Date().toISOString()
    }
  }
}
